RAILS_ROOT = "#{File.dirname(__FILE__)}/../.." unless defined?(RAILS_ROOT)
require "RMagick"

class MailManager < ActionMailer::Base
  
  include MailParser

  def receive(email)

    @permalink = /(\{[a-z0-9_]+\})?/
    @ref_permalink = /(\{[PI]=[a-z0-9_]+\})?/
    @tags = /\[([a-zA-Z0-9 ]+[,]?)+\]/
    @title = /[a-zA-Z0-9 ,!?;:]+/

    @reg_as_content = Regexp.new(".*("+@permalink.to_s+")("+@tags.to_s+")("+@title.to_s+")")
    @reg_as_comment = Regexp.new(".*("+@ref_permalink.to_s+")("+@title.to_s+")")

    content = parse_content(email)

    if email.from[0] == 'benoit.laffitte@gmail.com' then
      treat_as_post(email, content[:html]) if email.to[0] == 'post@benzo.fr'
      treat_image(email) if email.to[0] == 'image@benzo.fr'
    end
    treat_as_comment(email, content[:plain]) if email.to[0]== 'comment@benzo.fr'

  end

  private

  def treat_as_post(email, content)
    chunks = @reg_as_content.match(email.subject)
    post = nil
    if chunks.nil? or chunks[1].nil? then
      post = Post.new
    else
      reg_type_post = /\{([a-z0-9_]+)\}/
      id = reg_type_post.match(chunks[1])
      unless id.nil? or id[1].nil? then
        post = Post.find_last_by_permalink(id[1])
      else
        post = Post.new
      end
    end
    post.body = content
    post.title = email.subject.gsub(/.*((\{[a-z0-9_]+\})?)(\[([a-zA-Z0-9 ]+[,]?)+\])/,"").gsub(/^[ ]+/, "")
    post.permalink = sanitize_filename(post.title.downcase)
    treat_image(email)
    unless post.save! then
    end
    treat_tags(email, post)
  end

  def treat_image (email)
    if email.has_attachments?
      for attachment in email.attachments
        image = Image.find_last_by_permalink sanitize_filename(attachment.original_filename)
        image = Image.new if image.nil?
        image.name = sanitize_filename(attachment.original_filename) if image.name.nil?
        image.permalink = image.name.downcase.gsub(/\./, "_")
        save_attachement!(image, attachment)
        img = Magick::Image::read(image.path).first
        image.orientation = "P" if img.rows.to_f > img.columns.to_f
        image.orientation = "L" if img.rows.to_f < img.columns.to_f
        image.orientation = "C" if img.rows.to_f == img.columns.to_f
        unless image.save! then
          # mail erreur
        end
        treat_tags(email, image)
      end
    else
      # error mail
    end
  end

  def treat_tags(email, item)
    reg_tags  = Regexp.new ".*("+@tags.to_s+").*"
    chunks = reg_tags.match(email.subject)
    unless chunks.nil? or chunks[1].nil? then
      tags = chunks[1].split(/[\[\],]/)
      tags.each do |t|
        unless t.blank? then
          tag = Tag.find_last_by_name(t)
          unless tag  then
            tag =  Tag.new
            tag.name = t
            unless tag.save! then
            end
          end
          tag.images << item if item.is_a? Image
          tag.posts << item if item.is_a? Post
          unless tag.save! then
          end
        end
      end
    end
  end

  def treat_as_comment (email, content)
    reg_type_post = /\{P=([a-z0-9_]+)\}/
    reg_type_image = /\{I=([a-z0-9_]+)\}/
    chunks = @reg_as_comment.match(email.subject)
    comment = Comment.new
    comment.body = content
    comment.email = email.from[0]

    comment.name = email.subject.gsub(reg_type_post, "").gsub(reg_type_image, "")
    if(reg_type_post == chunks[1]) then
      comment.post = Post.find(reg_type_post.match(chunks[1])[1])
    end
    if(reg_type_image == chunks[1]) then
      comment.image = Image.find(reg_type_image.match(chunks[1])[1])
    end
    unless comment.save! then
      # mail erreur
    end
  end

  def save_attachement!(image, attachment)
    attachment.content_type.chomp
    # save original file
    image.path = Image.save_upload!(attachment)
  end

  def base_part_of(file_name)
    name = File.basename(file_name)
    name.gsub(/[^W._-]/, '')
    sanitize_filename(name)
  end

  # Fixes a 'feature' of IE where it passes the entire path instead of just the filename
  def sanitize_filename(value)
    #get only the filename (not the whole path)
    just_filename = value.gsub(/^.*(\\|\/)/, '')
    just_filename.gsub(/[^\w\.\-]/,'_')
  end

end
